import { Fragment, useState, useEffect } from "react";
import ChatWindow from "../ChatWindow/index.jsx";
import ChatOptions from "../ChatOptions/index.jsx";
import "./index.css";
import useChatX from "@/common/hooks/useChatX.js";
import { v4 as uuid } from "uuid";
import { XStream } from "@ant-design/x";
import { loadChatStream, loadGetSessionList, loadGetChatBySession } from "@/api/chat.js";
import AiChatContext from "@/common/context/aiChatContext.js";

const AiChat = function () {
  const page = {
    pageNum: 1,
    pageSize: 20,
  }
  // 这个是通知子组件，有对话了，需要渲染对话操作
  const [hasMsg, setHasMsg] = useState(false);

  const [sessionList, setSessionList] = useState([]);

  const { chatX, updateChatX, clearChatX } = useChatX();

  // 获取历史对话
  const requestHistoryChat = async (sessionId) => {
    // 每次查历史对话清空之前chatX
    clearChatX();
    const response = await loadGetChatBySession({ sessionId, ...page });
    const histroyList = response.data;
    if (histroyList.length) {
      for (const item of response.data) {
        updateChatX({
          chatId: item.chatId,
          role: item.role,
          status: "done",
          content: item.text,
          sessionId: item.sessionId,
        })
      }
      setHasMsg(true);
    } else {
      console.log("没有历史对话");
    }
  };

  // 获取session历史会话列表
  const getSessionList = async (sessionId) => {
    const response = await loadGetSessionList(sessionId);
    const list = response.res;
    setSessionList(list);
  };

  // 获取SSE对话流
  const requestFetch = async (params) => {
    // 用户对话
    updateChatX({
      chatId: uuid(),
      role: "user",
      status: "done",
      content: params.text,
      sessionId: params.sessionId,
    });

    const response = await loadChatStream(params);

    for await (const chunk of XStream({
      readableStream: response,
    })) {
      const data = JSON.parse(chunk.data);

      // 系统对话
      updateChatX({
        chatId: data.chatId,
        role: "system",
        status: data.sseType,
        content: data.outputMessage,
        sessionId: data.sessionId,
      });
    }
  };

  useEffect(() => {
    getSessionList();
  }, []);

  return (
    <Fragment>
      <AiChatContext.Provider
        value={{ chatX, hasMsg, setHasMsg, requestFetch, clearChatX, sessionList, requestHistoryChat }}
      >
        <div className="ai-chat">
          <ChatWindow />
        </div>
        <div className="ai-chat-options">
          <ChatOptions />
        </div>
      </AiChatContext.Provider>
    </Fragment>
  );
};

export default AiChat;
